package com.xixi.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;

@Component
public class FileUploadUtil {

    @Value("${file.upload-dir:src/main/resources/uploads}")
    private String uploadDir;

    public String uploadImage(MultipartFile file) throws Exception {
        String projectRoot = System.getProperty("user.dir");
        String fullUploadPath = projectRoot + File.separator + uploadDir + "/trading/images/products/";

        // 创建目录
        File dir = new File(fullUploadPath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                throw new Exception("无法创建目录: " + fullUploadPath);
            }
        }

        // 生成文件名
        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        String fileName = UUID.randomUUID() + extension;

        // 保存文件
        File dest = new File(fullUploadPath + fileName);
        file.transferTo(dest);

        return "/uploads/trading/images/products/" + fileName;
    }
}